// admin/system/dao/sys_user_post_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysUserPostDao 用户岗位关联数据访问接口
type SysUserPostDao interface {
	Create(userPost *model.SysUserPost) error
	GetByUserID(userID int64) ([]*model.SysUserPost, error)
	GetByPostID(postID int64) ([]*model.SysUserPost, error)
	DeleteByUserID(userID int64) error
	DeleteByPostID(postID int64) error
	DeleteByUserIDAndPostID(userID, postID int64) error
	ListPostIDsByUserID(userID int64) ([]int64, error)
	ListUserIDsByPostID(postID int64) ([]int64, error)
}

type sysUserPostDao struct {
	db *gorm.DB
}

// NewSysUserPostDao 创建用户岗位关联数据访问实例
func NewSysUserPostDao() SysUserPostDao {
	return &sysUserPostDao{
		db: database.GetDB(),
	}
}

func (up *sysUserPostDao) Create(userPost *model.SysUserPost) error {
	logger.Info("创建用户岗位关联",
		zap.Int64("user_id", userPost.UserID),
		zap.Int64("post_id", userPost.PostID))
	return up.db.Create(userPost).Error
}

func (up *sysUserPostDao) GetByUserID(userID int64) ([]*model.SysUserPost, error) {
	logger.Debug("根据用户ID获取用户岗位关联", zap.Int64("user_id", userID))
	var userPosts []*model.SysUserPost
	err := up.db.Where("user_id = ?", userID).Find(&userPosts).Error
	return userPosts, err
}

func (up *sysUserPostDao) GetByPostID(postID int64) ([]*model.SysUserPost, error) {
	logger.Debug("根据岗位ID获取用户岗位关联", zap.Int64("post_id", postID))
	var userPosts []*model.SysUserPost
	err := up.db.Where("post_id = ?", postID).Find(&userPosts).Error
	return userPosts, err
}

func (up *sysUserPostDao) DeleteByUserID(userID int64) error {
	logger.Info("根据用户ID删除用户岗位关联", zap.Int64("user_id", userID))
	return up.db.Where("user_id = ?", userID).Delete(&model.SysUserPost{}).Error
}

func (up *sysUserPostDao) DeleteByPostID(postID int64) error {
	logger.Info("根据岗位ID删除用户岗位关联", zap.Int64("post_id", postID))
	return up.db.Where("post_id = ?", postID).Delete(&model.SysUserPost{}).Error
}

func (up *sysUserPostDao) DeleteByUserIDAndPostID(userID, postID int64) error {
	logger.Info("根据用户ID和岗位ID删除用户岗位关联",
		zap.Int64("user_id", userID),
		zap.Int64("post_id", postID))
	return up.db.Where("user_id = ? AND post_id = ?", userID, postID).Delete(&model.SysUserPost{}).Error
}

func (up *sysUserPostDao) ListPostIDsByUserID(userID int64) ([]int64, error) {
	logger.Debug("根据用户ID获取岗位ID列表", zap.Int64("user_id", userID))
	var postIDs []int64
	err := up.db.Model(&model.SysUserPost{}).Where("user_id = ?", userID).Pluck("post_id", &postIDs).Error
	return postIDs, err
}

func (up *sysUserPostDao) ListUserIDsByPostID(postID int64) ([]int64, error) {
	logger.Debug("根据岗位ID获取用户ID列表", zap.Int64("post_id", postID))
	var userIDs []int64
	err := up.db.Model(&model.SysUserPost{}).Where("post_id = ?", postID).Pluck("user_id", &userIDs).Error
	return userIDs, err
}
